package my.convert.attribute.processor;

import java.beans.PropertyEditor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


public class MyPropertyEditorRegistrySupport extends PropertyEditorRegistrySupport {

	private Map<Class<?>, PropertyEditor> myEditors = new HashMap<>(16);


	@Override
	public PropertyEditor getDefaultEditor(Class<?> requiredType) {
		PropertyEditor defaultEditor = super.getDefaultEditor(requiredType);
		if(defaultEditor!=null)return defaultEditor;
		defaultEditor = myEditors.get(requiredType);
		if(defaultEditor !=null)return defaultEditor;
		//第一次调用，defaultEditor为空，会走下面逻辑。第二次及以后，下面的代码不会再重复执行，性能得以提升
		try {
			Field f = this.getClass().getSuperclass().getDeclaredField("defaultEditorsActive");
			f.setAccessible(true);
			f.set(this, true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.getDefaultEditor(requiredType);
	}


	public void addEditor(Class<?> clazz,PropertyEditor pe){
		myEditors.put(clazz,pe);
	}
	public void removeEditor(Class<?> clazz){
		myEditors.remove(clazz);
	}
}
